/**
 * @author Kevin.MOU
 * Login view script Support
 */
(function($) {

	window.$E = {
		device: 'pc'
	}
	const Login = {
		singleProject: true,
		useMobile: false,
		onRemember: function (e) {
			e.preventDefault();
			$("#remember").toggleClass('checkbox_checked');
		},
		onRememberAutoLogin: function (e) {
			e.preventDefault();
			$("#rememberAutoLogin").toggleClass('checkbox_checked');
		},

		onSubmit: function (username, password, remoteKey, verify) {
			let a = this, projects = [];
			if (a.singleProject) {
				if (Login.loginInfoType !== 2) {
					// if(!a.groupMenu.data || a.groupMenu.data.length === 0)
					// 	return showError($F.lang('noAccountError'));
					// 指定域名登录，需要限制登录组的账号
					if ($("#groupFix").val()) {
						projects.push({
							prjId: a.defaultProject.id,
							prjName: a.defaultProject.name,
							groupId : $("#groupFix").val(),
							dbPool: a.defaultProject.key
						});
					} else {
						let group = a.groupMenu.val();
						if (!group || !group.value) {
							return showError($F.lang('groupError'));
						} else {
							projects.push({
								prjId: a.defaultProject.id,
								prjName: a.defaultProject.name,
								groupId : Login.loginInfoType === 3 ? '#AUTO#' : group.value,
								dbPool: a.defaultProject.key
							});
						}
					}
				} else {
					projects.push({
						prjId: '',
						prjName: '',
						groupId: '',
						dbPool: ''
					});
				}
			} else {
				let checkedProject = $(".ps_left input[type=checkbox]:checked");
				if (checkedProject.length === 0) {
					projects.push({
						prjId: '',
						prjName: '',
						groupId: '',
						dbPool: ''
					});
					// return showError($F.lang('noProjectSelectedError'));
				}

				let executable = true;
				checkedProject.each(function (i, v) {
					let ckb = $(v),
						prjId = ckb.data("prjId"),
						prjName = ckb.data("prjName"),
						prjKey = ckb.data("prjKey"),
						group = ckb.data("groupSelector").val();
					if (! group) {
						showError('[' + prjName + ']' + $F.lang('projectNoGroupError'));
						executable = false;
						return false;
					}
					projects.push({
						prjId: prjId,
						prjName: prjName,
						groupId : group.value,
						// groupId: '#AUTO#',
						dbPool: prjKey
					});
				});
				if (! executable)
					return;
			}
			// console.info('Login projects: ', projects);

			busy(1, $F.lang('submit'));
			let loginRequest = {
				useLang: a.language,
				standFlag: 1,
				cacheFlag: 1,
				clientFlag: 1,
				epid: '',
				loginId: username,
				password: $F.encPwd(password, a),
				remoteInfo: remoteKey,
				subProjectList: [],
				projects: projects,
				uid: a.uid
			};
			if (Login.thirdlVGroovyUrl)
				loginRequest.thirdPassword = $F.encPwd(password, a, true);
			let dataRequest = $.extend(a.requestQueries, {
				uid: a.uid,
				ecsid: 'ngs',
				captcha: (verify ? verify.toUpperCase() : ''),
				language: a.language,
				payload: JSON.stringify(loginRequest)
			});
			Ajax.post({
				url: 'login_',
				data: dataRequest,
				success: function (data) {
					// console.log(data);
					if (data.code > 0) {
						if ($("#remember").hasClass("checkbox_checked")) {
							$.cookie("remember_username", username, {
								expires: 30
							});
							$.cookie('remember_groupId', projects[0].groupId, {
								expires: 30
							});
							// if ($('#rememberAutoLogin').hasClass("checkbox_checked")) {
							// 	$.cookie("remember_auto_login", "1", {
							// 		expires: 30
							// 	});
							// 	$.cookie("remember_password", password, {
							// 		expires: 30
							// 	});
							// } else {
							// 	$.cookie("remember_auto_login", null);
							// 	$.cookie("remember_password", null);
							// }
							//console.log("Save cookies: remember_username=" + username + ', remember_groupId=' + projects[0].groupId);
						} else {
							$.cookie("remember_username", null);
							$.cookie("remember_groupId", null);
							// $.cookie("remember_auto_login", null);
							// $.cookie("remember_password", null);
							//console.log("Remove cookies: remember_username");
						}
						$('#vid').hide();
						location.href = data.message + '?po=elitengs';
					} else {
						refreshVerify();
						switch (data.code) {
							case -7:
								// 重复登录
								if (a.forceLoginAllow) {
									$F.confirm('<span style="color:red;font-size: 1.2em">' + $F.lang('forceLoginTip') + '</span>', function() {
										if (data.value)
											a.onForceSubmit(data.value, username, '', projects);
										else
											showError($F.lang('forceLoginError'))
									}, false, {
										htmlallow: true
									})
								} else {
									showError(data.message);
								}
								break;
							case -101:	// 密码为空
								a.pwdChange(username, '', projects, $F.lang('pwdEmpty'));
								break;
							case -102:	// 密码过期
								a.pwdChange(username, '', projects, $F.lang('pwdExpired'));
								break;
							case -103:	// 密码过期（无修改时间）
								a.pwdChange(username, '', projects, $F.lang('pwdInited'));
								break;
							default:
								showError(data.message);
						}
						busy(0);
					}
				},
				fail: function (jqXHR, textStatus) {
					showError(textStatus);
					busy(0);
				}
			});
		},

		checkMobileSAAS: function (epid, username, password, remoteKey, verify) {
			if (Login.useMobile) { // 使用手机登录saas，先判断此手机是在那个epid的
				let form = $("form.login_form"),
					mobile = $('input#mobile', form).val();
				Ajax.post({
					url: getServiceMethod('JSGenerateServlet2_1'),
					data: JSON.stringify({
						name: 'System.login.info',
						sqlKey: 'System.Login.getEPByMobile',
						paras: [mobile]
					}),
					headers: {
						THREADID: Date.now(),
						DS: Login.dataService.key
					},
					contentType: 'json',
					success: function (data, textStatus, jqXHR) {
						if (data.code > 0) {
							data.value = Ajax.d(data.value, jqXHR);
							if (data.value && data.value.length > 0) {
								if (data.value.length === 1) {
									epid = data.value[0][0];
									Login.onSubmitSAAS(epid, mobile, password, remoteKey, verify);
								} else {
									// show ep_container
									$('.login_box').hide();
									let panel = $('.selectep_panel').show();
									panel.css('margin', '-' + (panel.outerWidth() / 2) + 'px');
									$('.ep_container', panel).empty();
									data.value.forEach(function (ep) {
										$('.ep_container', panel).append('<a href="javascript:;" data-epid="' + ep[0] + '" class="ep"><img src="' + ep[2] + '" class="ep_logo" /><span class="ep_name">' + ep[1] + ' (' + ep[0] + ')</span></a>');
									});
									$('.ep_container a', panel).on('click', function () {
										epid = $(this).attr('data-epid');
										Login.onSubmitSAAS(epid, mobile, password, remoteKey, verify);
										$('.login_box').show();
										$('.selectep_panel').hide();
									});
								}
							} else {
								showError($F.lang('noAccountError'));
							}
						} else {
							showError(data.message);
						}
					}
				});
			} else {
				Login.onSubmitSAAS(epid, username, password, remoteKey, verify);
			}
		},

		onSubmitSAAS: function (epid, username, password, remoteKey, verify) {
			let a = this;
			if (epid == '')
				epid = 'MainDB';
			else
				epid = epid.toUpperCase();

			busy(1, $F.lang('submit'));
			let dataRequest = $.extend(a.requestQueries, {
				uid: a.uid,
				ecsid: 'ngs',
				captcha: (verify ? verify.toUpperCase() : ''),
				language: a.language,
				payload: JSON.stringify({
					useLang: a.language,
					standFlag: 0,
					cacheFlag: 1,
					clientFlag: 1,
					epid: epid,
					loginId: username,
					password: $F.encPwd(password, a),
					remoteInfo: remoteKey,
					subProjectList: [],
					projects: [],
					uid: a.uid
				})
			});
			Ajax.post({
				url: 'login_',
				data: dataRequest,
				success: function (data) {
					if (data.code > 0) {
						if ($("#remember").hasClass("checkbox_checked")) {
							if (Login.useMobile) {
								$.cookie("remember_mobile", username, {
									expires: 30
								});
							} else {
								$.cookie("remember_username", username, {
									expires: 30
								});
							}
							$.cookie("remember_epid", epid, {
								expires: 30
							});
							if ($('#rememberAutoLogin').hasClass("checkbox_checked")) {
								$.cookie("remember_auto_login", "1", {
									expires: 30
								});
								$.cookie("remember_password", password, {
									expires: 30
								});
							} else {
								$.cookie("remember_auto_login", null);
								$.cookie("remember_password", null);
							}
							//console.log("Save cookies: remember_epid, remember_username");
						} else {
							$.cookie("remember_username", null);
							$.cookie("remember_epid", null);
							$.cookie("remember_auto_login", null);
							$.cookie("remember_password", null);
							//console.log("Remove cookies: remember_epid, remember_username");
						}
						$('#vid').hide();
						location.href = data.message;
					} else {
						refreshVerify();
						switch (data.code) {
							case -7:
								// 重复登录
								if (a.forceLoginAllow) {
									$F.confirm('<span style="color:red;font-size: 1.2em">' + $F.lang('forceLoginTip') + '</span>', function() {
										if (data.value)
											a.onForceSubmit(data.value, username, '', projects);
										else
											showError($F.lang('forceLoginError'))
									}, false, {
										htmlallow: true
									})
								} else {
									showError(data.message);
								}
								break;
							case -101:	// 密码为空
								a.pwdChange(username, epid, [], $F.lang('pwdEmpty'));
								break;
							case -102:	// 密码过期
								a.pwdChange(username, epid, [], $F.lang('pwdExpired'));
								break;
							case -103:	// 密码过期（无修改时间）
								a.pwdChange(username, epid, [], $F.lang('pwdInited'));
								break;
							default:
								showError(data.message);
						}
						busy(0);
					}
				},
				fail: function (jqXHR, textStatus) {
					showError(textStatus);
					busy(0);
				}
			});
		},

		onForceSubmit: function (forceId, username, epid, projects) {
			let a = this,
				dataRequest = $.extend(a.requestQueries, {
					language: a.language,
					ds: a.dataService.key,
					forceId: forceId,
					uid: a.uid
				});
			busy(1, $F.lang('submit'));
			Ajax.post({
				url: 'loginForce_',
				data: dataRequest,
				success: function (data) {
					//console.log(data);
					if (data.code > 0) {
						location.href = data.message;
					} else {
						switch (data.code) {
							case -101:	// 密码为空
								a.pwdChange(username, epid, projects, $F.lang('pwdEmpty'));
								break;
							case -102:	// 密码过期
								a.pwdChange(username, epid, projects, $F.lang('pwdExpired'));
								break;
							case -103:	// 密码过期（无修改时间）
								a.pwdChange(username, epid, projects, $F.lang('pwdInited'));
								break;
							default:
								showError(data.message);
						}

						busy(0);
					}
				},
				fail: function (jqXHR, textStatus, errorThrown) {
					showError(textStatus);
					busy(0);
				}
			})
		},

		pwdForgotSendCode(e) {
			const form = $('form.login_pwdreset');
			let username = $("input[name=username]", form).val();
			$("#pc_err").text('').hide();
			if (! username) {
				$("#pc_err").text($F.lang('loginNameEmptyError')).show();
				return;
			}
			Ajax.post({
				url: Login.url + '/loginSendAuthCode?t=' + Date.now(),
				data: {
					uid: Login.uid,
					ecsid: 'ngs',
					epid: '',
					username: username,
					dbpool: '',
					ds: Login.dataService.key
				},
				success : function(data) {
					if (data.code > 0) {
						$F.info(data.message);
						$("#pc_err").text('');
						makeVerifyState($(e.target));
					} else {
						$("#pc_err").text(data.message).show();
					}
				}
			})
		},

		pwdforgot: function () {
			$('.login_panel').hide();
			let a = this,
				panel = $('.pwdchange').show(),
				err = $('.pc_err', panel).text('').show();
			$('input[name=oldpwd]', panel).parent().hide();
			$('input[name=pwdforgot-code]', panel).val('').parent().show();
			$('input[name=username]', panel).val('').parent().show();
			$('input[name=newpwd]', panel).val('');
			$('input[name=newpwd2]', panel).val('');

			$('.js_cancel', panel).off('click').on('click', function () {
				panel.hide();
				$('.login_panel').show();
			})
			$('.js_submit', panel).off('click').on('click', function () {
				let pwdforgotCode = $('input[name=pwdforgot-code]', panel).focus(),
					username = $('input[name=username]', panel),
					newpwd = $('input[name=newpwd]', panel),
					newpwd2 = $('input[name=newpwd2]', panel);

				if (!username.val()) {
					err.text($F.lang('loginNameEmptyError')).show();
					username.focus();
					return;
				}
				if (!pwdforgotCode.val()) {
					err.text($F.lang('codeEmpty')).show();
					pwdforgotCode.focus();
					return;
				}
				if (!newpwd.val()) {
					err.text($F.lang('newPwdNoEmptyError')).show();
					newpwd.focus();
					return;
				}
				if (newpwd2.val() !== newpwd.val()) {
					err.text($F.lang('wrongRepeatPwdError')).show();
					newpwd2.focus();
					return;
				}
				Ajax.post({
					url: Login.url + '/loginPwdReset?t=' + Date.now(),
					data: {
						epId: '',
						ecsid: 'ngs' + username.val(),
						code: pwdforgotCode.val(),
						dbPool: '',
						loginId: username.val(),
						n: newpwd.val(),
						uid: a.uid
					},
					success: function (data, textStatus, jqXHR) {
						if (data.code > 0) {
							data.value = Ajax.d(data.value, jqXHR);
							panel.hide();
							$('.login_panel').show();
							showError($F.lang('pwdModifiedAndRelogin'))
						} else {
							err.text(data.message).show();
						}
					}
				})
			})
		},

		/**
		 *
		 * @param username
		 * @param epid
		 * @param projects
		 * @param message
		 * @param type  1: 忘记密码  2：修改密码
		 */
		pwdChange: function (username, epid, projects, message, type) {
			$('.login_panel').hide();

			let a = this,
				panel = $('.pwdchange').show(),
				err = $('.pc_err', panel).text(message).show(),
				project = $('select[name="project"]', panel).empty(),
				projectDom = $('.pwdchange .selectProject');
			$('#pwdforgot-code').parent().hide();
			$('input[name=username]', panel).parent().hide();
			$('input[name=oldpwd]', panel).parent().show();
			$('.js_submit', panel).show();
			$('.js_cancel', panel).show();
			if (epid) {
				project.append('<option value="">' + epid + '</option>');
			} else {
				let dbpool = a.dataService.dbPool;
				$.each(projects, function (i, v) {
					project.append('<option value="' + (v.prjKey ? (dbpool + '-' + v.prjKey) : dbpool) + '">' + v.prjName + '</option>');
				})
			}
			if (projects.length === 1) {
				projectDom.hide()
			} else {
				projectDom.show()
			}

			$('.js_cancel', panel).off('click').on('click', function () {
				panel.hide();
				$('.login_panel').show();
			})
			$('.js_submit', panel).off('click').on('click', function () {
				let oldpwd = $('input[name=oldpwd]', panel).focus(),
					newpwd = $('input[name=newpwd]', panel),
					newpwd2 = $('input[name=newpwd2]', panel);

				if (!newpwd.val()) {
					err.text($F.lang('newPwdNoEmptyError')).show();
					newpwd.focus();
					return;
				}
				if (newpwd2.val() !== newpwd.val()) {
					err.text($F.lang('wrongRepeatPwdError')).show();
					newpwd2.focus();
					return;
				}

				let sqldata = {
					name: "System.StaffInfo.ChangeN",
					epId: epid,
					dbPool: a.dataService.dbPool,
					loginId: username,
					o: $F.encPwd(oldpwd.val(), a),
					n: $F.encPwd(newpwd.val(), a, true),
					uid: a.uid
				}
				// console.info('Change password', sqldata)
				Ajax.post({
					url: getServiceMethod('JSGenerateServlet2_1'),
					data: JSON.stringify(sqldata),
					headers: {
						THREADID: Date.now(),
						DS: a.dataService.key
					},
					contentType: 'json',
					success: function (data, textStatus, jqXHR) {
						if (data.code > 0) {
							data.value = Ajax.d(data.value, jqXHR);
							panel.hide();
							$('.login_panel').show();
							showError($F.lang('pwdModifiedAndRelogin'))
						} else {
							// console.log(data)
							if (data.code == -7)
								err.text($F.lang('wrongOriginalPwdError')).show();
							else
								err.text(data.message).show();
						}
					}
				})
			})
		}
	};
	window.Login = Login;

	const init = function() {
			Login.rsaPubKey = $('input#rsaPubKey').val();
			Login.requestQueries = $.extend(true, Login.defaultMode, Request.queryStrings());
			let cs = [];
			for(let key in Login.languages) {
				cs.push({
					value: key,
					label: Login.languages[key]
				})
			}
			$('.login_language').wisCombox({
				tip : $F.lang('language'),
				onSelected : function(data) {
					$.cookie("language", data.value, {
						expires : 30
					});
					location.reload(true);
				}
			}).setData(cs).val(Login.language);

			$.cookie("language", Login.language, {
				expires : 30
			});

			$('a.ocx_btn').click(function(e){
				e.preventDefault();
				window.open(Login.url + '/downloads/EliteLocalProxy.exe');
			});
			$('.login_sso').click(function(e) {
				location.href = Login.url + '/logout';
			});

			$('#passwordeye').click(function (e) {
				if ($(this).hasClass('invisible')) {
					$(this).removeClass('invisible').addClass('visible');//密码可见
					$('input#password').prop('type', 'text');
				} else {
					$(this).removeClass('visible').addClass('invisible');//密码不可见
					$('input#password').prop('type', 'password');
				}
			});

			if (Login.dataService.saas) {
				// SAAS模式登录
				if (!Login.epid) {
					$('.login_epid').show();
				}
				// $('.login_group').hide();
				$('.login_projects').hide();

				// 设置输入中的回车
				$("input#epid").keydown(function(e) {
					if (e.keyCode === 13) {
						e.preventDefault();
						$("input#username").select().focus();
					}
				});
				let unInput = $("input#username").keydown(function(e) {
					if (e.keyCode === 13) {
						e.preventDefault();
						$("input#password").select().focus();
					}
				});

				// 加载手机登录模式
				if (Login.enableSAASMobileLogin) {
					$('.login_way_tab').show();
					$('.account_login').on('click', function() {
						$('.mobile_login').removeClass('cur');
						$('.account_login').addClass('cur');
						if (!Login.epid) {
							$('.login_epid').show();
						}
						$('.login_username').show();
						$('input#username').attr('required', 'required');
						$('.login_mobile').hide();
						$('input#mobile').removeAttr('required');
						Login.useMobile = false;
						$.cookie('remember_login_way', 'account', {
							expires: 30
						});
					});
					$('.mobile_login').on('click', function() {
						$('.account_login').removeClass('cur');
						$('.mobile_login').addClass('cur');
						$('.login_epid').hide();
						$('.login_username').hide();
						$('input#username').removeAttr('required');
						$('.login_mobile').show();
						$('input#mobile').attr('required', 'required');
						Login.useMobile = true;
						$.cookie('remember_login_way', 'mobile', {
							expires: 30
						});
					});
				}

				// 取cookie值
				let username = $.cookie("remember_username"),
					epid = $.cookie("remember_epid"),
					mobile = $.cookie("remember_mobile"),
					loginWay = $.cookie('remember_login_way');
				if (username != null || mobile != null) {
					$("#remember").addClass("checkbox_checked");
					if (username != null) {
						$("input#epid").val(epid);
						if (! unInput.val())
							unInput.val(username);
					}
					if (mobile != null) {
						if (! $("input#mobile").val()) {
							$("input#mobile").val(mobile);
						}
					}
				} else {
					$("#remember").removeClass("checkbox_checked");
					$("input#epid").val('');
					$("input#username").val('');
					$("input#mobile").val('');
				}
				if (loginWay === 'mobile') {
					$('.mobile_login').click();
					$("input#mobile").focus();
				} else {
					if (!Login.epid) {
						$("input#epid").focus();
					} else {
						$("input#username").focus();
					}
				}
			} else {
				// 普通模式登录
				$('.login_epid').hide();

				// initialize group combox
				Login.groupMenu = $("div#group").wisCombox({
					tip : $F.lang('groupChoice'),
					onSelected : function(data) {
						if (data)
							console.log('Selected group:' + data.value);
					}
				});
				// initialize username input
				let unInput = $('input#username').on('change', function(e) {
					let username = $(e.target).val();
					if (username === Login.username)
						return;
					Login.username = username;
					Login.groupMenu.setData([]);
					if (! username) {
						Login.projects = {};
						Login.singleProject = false;
						return;
					}
					if (Login.loginInfoType !== 2) {
						Login.singleProject = false;
						loadProjects(username);
					} else {
						let pd = $("div.login_projects").hide();
						$("ul", pd).empty();
						$('.login_group').hide();
						//Login.groupMenu.setData([]);
						Login.singleProject = true;
						delete Login.defaultProject;
					}
				});

				// SSO登录情况下， 不要去判断获取到的cookie值，不然有问题( 如果获取不到remember_username cookie值会把之前获取到的登录名清空)
				if (unInput.prop('disabled')) {
					unInput.trigger('change');
				} else {
					// 取cookie值
					let username = $.cookie("remember_username");
					if (username !== null) {
						$("#remember").addClass("checkbox_checked");
						if (! unInput.val())
							unInput.val(username);
					} else {
						$("#remember").removeClass("checkbox_checked");
						$("input#username").val('');
						$("input#password").val('');
					}
				}
				unInput.focus().trigger('change');
			}

			const form = $('form.login_form');
			if (Login.verifyAuth === 'image') {
				$('img.verifyCode', form).on('click', function(e) {
					//console.log('Change verify code')
					var src = $(this).attr('src');
					src = src.substring(0, src.lastIndexOf('&'));
					$(this).attr('src', src + '&t=' + Date.now())
				});
			} else if (Login.verifyAuth === 'sms') {
				$('button.verifyCode', form).on('click', function(e) {
					let epid = $("input#epid", form).val(),
						username = $("input#username", form).val(),
						password = $("input#password", form).val();
					if (! username)
						return showError($F.lang('loginNameEmptyError'));

					$(".login_err_panel").hide();
					$F.await(function(go){
						Ajax.post({
							url: Login.url + '/loginVerify_?t=' + Date.now(),
							data: {
								c: 'sms',
								uid: Login.uid,
								ecsid: 'ngs',
								epid: epid,
								username: username,
								password: $F.encPwd(password, Login),
								dbpool: '',
								ds: Login.dataService.key
							},
							success : function(data) {
								if (data.code > 0) {
									$F.info(data.message);
									makeVerifyState($(e.currentTarget))
								} else
									showError(data.message);
							},
							always: function() {
								go();
							}
						})
					});
				});
			}

			Login.verifier = $('div.login_verify', form);
			if (Login.verifyLock || Login.verifyAuthTrigger === 'always') {
				Login.verifier.show();
			} else {
				Login.verifier.appendTo($('body'));
			}

			function do_login() {
				const epid = $("input#epid", form).val(),
					username = $("input#username", form).val(),
					password = $("input#password", form).val();

				// console.log(password);
				let remoteKey = localStorage.getItem("elite_remote_key");
				if (!remoteKey) {
					remoteKey = Guid.raw();
					localStorage.setItem("elite_remote_key", remoteKey);
				}

				$(".login_err_panel").hide();
				if (Login.errorMessage) {
					Login.slideLock = true;
					showError(Login.errorMessage);
				} else {
					if (Login.verifyLock && $('body').hasClass('slider')) {
						SlideUnlocker.init({
							lang: Login.language,
							onLoad: function(callback) {
								Ajax.post({
									url: Login.url + '/slidelock/load',
									data: {
										uid: Login.uid,
										ecsid: 'ngs'
									},
									dataType: 'binary',
									success: function(data) {
										callback(data);
									}
								})
							},
							onVerify : function(pos, callback) {
								Ajax.post({
									url: Login.url + '/slidelock/verify',
									data: {
										uid: Login.uid,
										ecsid: 'ngs',
										pos: pos
									},
									success: function(data) {
										callback(data, function() {
											if (Login.dataService.saas)
												Login.checkMobileSAAS(epid, username, password, remoteKey, $('input#verify').val());
											else
												Login.onSubmit(username, password, remoteKey, $('input#verify').val());
										});
									}
								})
							}
						})
					} else {
						if (Login.dataService.saas)
							Login.checkMobileSAAS(epid, username, password, remoteKey, $('input#verify').val());
						else
							Login.onSubmit(username, password, remoteKey, $('input#verify').val());
					}
				}
			}

			$("input#password", form).on('keypress', function(e) {
				if (e.keyCode === 13) do_login()
			});
			$('button.login_btn', form).on('click', function() {
				do_login()
			});

			// 自动登录
			if (Login.singleProject) {
				if ($.cookie("remember_auto_login") == 1) {
					$("input#password").val($.cookie("remember_password"));
					$("#rememberAutoLogin").addClass("checkbox_checked");
					$('form.login_form').submit();
				}
			}

			const loginBox = $('.login_box');
			loginBox.css('margin-top', loginBox.outerHeight() / -2);
		},

		refreshVerify = function() {
			if (Login.verifyAuthTrigger === 'onerror') {
				Login.verifyLock = true;
				$('div.login_help_panel').before(Login.verifier.show());
			}
			if (Login.verifyAuth === 'image') {
				$('img.verifyCode').click();
				$('input#verify').val('');
			}
		},

		makeVerifyState = function(t) {
			t.attr('disabled', true);
			t.forceClass('disabled');
			let wait = function(v) {
				t.text(v + $F.lang('verifyProcess'));
				v --;
				if (v > 0)
					setTimeout(function(){
						wait(v)
					}, 1000)
				else
					t.removeClass('disabled').attr('disabled', false).text($F.lang('verify'));
			}
			wait(60);
		},

		getServiceMethod = function(method) {
			if (Login.dataService.api) {
				return Login.url + '/proxy?method=' + method;
			} else {
				return Login.dataService.url + '/' + method;
			}
		},

		loadProjects = function(un) {
			busy(1, $F.lang('loadGroups'));
			$("div.login_projects ul").empty();
			var data = JSON.stringify({
				operate : 'StandProject',
				epid : Login.dataService.dbPool,
				loginName : un
			});
			Ajax.post({
				url : Login.loginInfoType === 1 ? Login.url + '/loginInfo' : getServiceMethod('LoginInfo'),
				data : data,
				headers : {
					THREADID: Date.now(),
					DS: Login.dataService.key,
					SIGNER: md5(data)
				},
				contentType : 'json',
				async: false,
				success : function(data, textStatus, jqXHR) {
					if (data.code > 0) {
						data.value = Ajax.d(data.value, jqXHR);
						let projects = {};
						$.each(data.value.fields, function(i, v){
							if (! projects[v[0]]) {
								projects[v[0]] = {};
								projects[v[0]].groups = [];
							}
							projects[v[0]].id = v[0];
							projects[v[0]].name = v[1];
							projects[v[0]].key = v[5];
							projects[v[0]].groups.push({
								label: v[3],
								value: v[2]
							})
						});
						Login.projects = projects;
						let size = Object.keys(projects).length;
						if (size === 0) {
							let pd = $("div.login_projects").hide();
							$("ul", pd).empty();
							$('.login_group').hide();
							Login.groupMenu.setData([]);
							Login.singleProject = true;
							delete Login.defaultProject;
							showError($F.lang('noAccountError'));
						} else if (size === 1) {
							Login.singleProject = true;
							let project = Login.defaultProject = projects[Object.keys(projects)[0]];
							var defGroupId = $.cookie("remember_groupId");
							// console.log(defGroupId);
							Login.groupMenu.setData(project.groups);
							// 如果只有个组，则直接选中这个组
							if (project.groups.length === 1) {
								Login.groupMenu.val(project.groups[0].value);
								$('.login_group').hide();
							} else {
								// 多个组的时候，如果上次cookie中记住的组存在，且还在可选的组范围中，则选中这个记住的组
								let findDefGroup = false;
								if (defGroupId) {
									$.each(project.groups, function(i, g) {
										if (g.value === defGroupId) {
											findDefGroup = true;
										}
									});
								}
								if (findDefGroup) {
									Login.groupMenu.val(defGroupId);
								} else {
									Login.groupMenu.select();
								}
								if (!$("#groupFix").val()) {
									$(".login_group").show();
								}
							}
							$("div.login_projects").hide();
							$(".login_err_panel").hide();

							// 当SSO登录情况 如果当前登录人只有一个组 或者如果多个组的情况下想不选择组使用默认组登录则直接登录
							// 如使用$('form.login_form').submit(); 转发过来的请求直接使用sunmit会有问题。
							if ($('input#username').prop('disabled') && (project.groups.length === 1 || Login.loginInfoType === 3)) {
//							    $('form.login_form').submit();
								let remoteKey = localStorage.getItem("elite_remote_key");
								if (!remoteKey) {
									remoteKey = Guid.raw();
									localStorage.setItem("elite_remote_key", remoteKey);
								}
								if (Login.loginInfoType === 3) {$('.login_group').hide();}
								Login.onSubmit($('input#username').val(), '', remoteKey, $('input#verify').val());
							}
						} else {
							Login.singleProject = false;
							$("div.login_group").hide();
							let pd = $("div.login_projects").show(), ul = $("ul", pd).empty();
							for (let key in projects) {
								let project = projects[key],
									li = $("<li/>").appendTo(ul),
									right = $('<div class="ps_right" />').appendTo(li),
									selector = $('<div class="pr_selector disabled" />').appendTo(right),
									gs = selector.wisCombox({
										tip : $F.lang('groupChoice'),
										onSelected : function(data) {
											console.log('Selected:' + data.value);
										}
									}).setData(project.groups).select().disable(true),
									left = $('<div class="ps_left" />').appendTo(li),
									ckb = $('<input type="checkbox" id="ckb_' + key + '" />').appendTo(left);
								ckb.data("groupSelector", gs);
								ckb.data("prjKey", project.key);
								ckb.data("prjName", project.name);
								ckb.data("prjId", project.id);
								ckb.on('click', function(e){
									let $this = $(e.currentTarget);
									$this.data('groupSelector').disable(! $this.prop('checked'))
								});
								$('<label for="ckb_' + key + '">' + project.name + '</label>').appendTo(left);
							}
							delete Login.errorMessage;
						}
					} else {
						let pd = $("div.login_projects").hide();
						$("ul", pd).empty();
						// $(".login_group").show();
						// Login.groupMenu.setData([]);
						// Login.singleProject = true;
						// delete Login.defaultProject;

						// 不去提示异常，避免被人通过这个异常提示来遍历账号
						// if (data.code == -19) {
						//     // console.error(data);
						//     showError($F.lang('exception') + data.value ? data.value : '');
						// } else
						//     showError($F.lang('noAccountError'));
					}
				},
				fail: function(jqXHR, textStatus) {
					showError($F.lang('exception') + textStatus);
				},
				always : function() {
					busy(0);
				}
			});
		},

		busy = function(e, m) {
			if (e == 1) {
				$(".login_btn").hide();
				$(".login_busy").show().find('>span').text(m);
			} else {
				$(".login_busy").hide().find('>span').text('');
				$(".login_btn").show();
			}
		},

		showError = function(e) {
			$("#err_tips").text(e);
			$(".login_err_panel").show();
		},

		resizeBackground = function() {
			let bg = $('#bgDiv'),
				vid = $('#vid'),
				docHeight = $('body').innerHeight(),
				docWidth = $('body').innerWidth(),
				rate = 1.777777777777778;

			if (docWidth / docHeight > rate) {
				let vh = docWidth / rate;
				if (vh > docHeight) {
					bg.css({
						left: 0,
						top: (docHeight - vh) /2 + 'px'
					})
				} else {
					bg.css({
						left: 0,
						top: 0
					})
				}
				bg.css({
					width: docWidth,
					height: vh
				})
			} else {
				let vw = docHeight * rate;
				if (vw > docWidth) {
					bg.css({
						left: (docWidth - vw) /2 + 'px',
						top: 0
					})
				} else {
					bg.css({
						left: 0,
						top: 0
					})
				}
				bg.css({
					width: vw,
					height: docHeight
				})
			}
		};

	$(function() {

		let bg = $('#bgDiv'), vid = $('#vid'), img = new Image();
		$(window).on('resize', function(e){
			resizeBackground()
		}).trigger('resize');

		img.src = Login.url + '/images/background.jpg';
		img.onload = function() {
			bg.css({
				opacity: 1,
				backgroundImage : 'url(' + img.src + ')'
			})
		};

		vid.bind('canplay', function() {
			// console.log('Animation loaded')
			vid.css({opacity: 0.5})
		});

		init();
		localStorage.setItem('screenStatus', 0)
	});
})(jQuery);
